package com.eati.cm.config;

import com.eati.cm.auth.AuthFailHandler;
import com.eati.cm.auth.AuthSuccHandler;
import com.eati.cm.auth.CmAuthFilter;
import com.eati.cm.auth.CmUserAuthProvider;
import com.eati.cm.serv.ILoginServ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConf extends WebSecurityConfigurerAdapter {

    @Autowired
    ILoginServ loginServ;
    
    @Autowired
    AuthSuccHandler authSuccHandler;

    @Autowired
    AuthFailHandler authFailHandler;
    
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    
    
    @Bean
    CmUserAuthProvider instCmUserAuthProvider() {
    	return new CmUserAuthProvider(loginServ);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(loginServ);
        auth.authenticationProvider(instCmUserAuthProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	http.authorizeRequests()
    		.antMatchers("/error").permitAll()
    		.anyRequest().authenticated()
    		.and().formLogin().successHandler(authSuccHandler)
    							.failureHandler(authFailHandler);
    	http.addFilterAt(new CmAuthFilter(authenticationManagerBean(), loginServ), UsernamePasswordAuthenticationFilter.class);
    }
}
